const express = require('express');
const router = express.Router();
const Order = require('../models/Order');
const Product = require('../models/Product');
const User = require('../models/User');

// 1. 创建订单 - POST /api/orders
router.post('/', async (req, res) => {
  try {
    const { userId, items, address } = req.body;
    
    // 验证用户是否存在
    const user = await User.findById(userId);
    if (!user) return res.status(404).json({ success: false, message: '用户不存在' });

    // 计算总积分并验证商品库存
    let totalPoints = 0;
    const productChecks = items.map(async (item) => {
      const product = await Product.findById(item.itemId);
      if (!product) throw new Error(`商品 ${item.itemId} 不存在`);
      if (product.stock < item.quantity) throw new Error(`商品 ${product.name} 库存不足`);
      totalPoints += product.points * item.quantity;
      return product;
    });
    const products = await Promise.all(productChecks);

    // 验证用户积分是否足够
    if (user.points < totalPoints) {
      return res.status(400).json({ success: false, message: '积分不足' });
    }

    // 创建订单
    const order = new Order({
      userId,
      points: totalPoints,
      items: items.map((item, index) => ({
        itemId: item.itemId,
        name: products[index].name,
        quantity: item.quantity,
        points: products[index].points
      })),
      type: products[0].type, // 假设订单中商品类型一致
      address
    });
    await order.save();

    // 扣除用户积分并记录明细
    user.points -= totalPoints;
    user.pointDetails.push({
      detailId: `detail_${Date.now()}`,
      change: -totalPoints,
      type: '兑换',
      orderId: order._id
    });
    await user.save();

    // 减少商品库存
    await Promise.all(products.map(async (product, index) => {
      product.stock -= items[index].quantity;
      await product.save();
    }));

    res.status(201).json({ success: true, message: '订单创建成功', data: order });
  } catch (err) {
    res.status(400).json({ success: false, message: '订单创建失败', error: err.message });
  }
});

// 2. 获取订单详情 - GET /api/orders/{orderId}
router.get('/:orderId', async (req, res) => {
  try {
    const { orderId } = req.params;
    // 新增：校验 orderId 是否为有效的 MongoDB ObjectId
    if (!mongoose.Types.ObjectId.isValid(orderId)) { // 此处需要 mongoose 已定义
      return res.status(400).json({ success: false, message: '订单ID格式无效' });
    }

    const order = await Order.findById(orderId).populate('userId', 'nickname phone');
    if (!order) {
      return res.status(404).json({ success: false, message: '订单不存在' });
    }

    res.json({ success: true, data: order });
  } catch (err) {
    res.status(500).json({ success: false, message: '服务器错误', error: err.message });
  }
});

// 3. 获取用户订单列表 - GET /api/orders/{userId}
router.get('/orders/:userId', async (req, res) => {
  try {
    // 修正：将排序字段从 createdAt 改为模型中实际的 createTime
    const orders = await Order.find({ userId: req.params.userId }).sort({ createTime: -1 });
    if (!orders || orders.length === 0) {
      return res.status(404).json({ success: false, message: '未找到订单' });
    }

    res.json({ success: true, data: orders });
  } catch (err) {
    res.status(500).json({ success: false, message: '服务器错误', error: err.message });
  }
});

// 4. 更新订单状态 - PUT /api/orders/{orderId}/status
router.put('/:orderId/status', async (req, res) => {
  try {
    const { status } = req.body;
    const order = await Order.findByIdAndUpdate(
      req.params.orderId,
      { status },
      { new: true, runValidators: true }
    );
    if (!order) return res.status(404).json({ success: false, message: '订单不存在' });
    res.json({ success: true, message: '订单状态更新成功', data: order });
  } catch (err) {
    res.status(400).json({ success: false, message: '状态更新失败', error: err.message });
  }
});

// 5. 取消订单（积分退回） - DELETE /api/orders/{orderId}
router.put('/:orderId', async (req, res) => {
  try {
    const order = await Order.findById(req.params.orderId);
    if (!order) return res.status(404).json({ success: false, message: '订单不存在' });
    if (order.status !== '待发货') {
      return res.status(400).json({ success: false, message: '仅允许取消待发货订单' });
    }
    //更改订单状态为取消
    order.status = '已取消';
    await order.save();
    // 退回积分
    const user = await User.findById(order.userId);
    user.points += order.points;
    user.pointDetails.push({
      detailId: `detail_${Date.now()}`,
      change: order.points,
      type: '取消订单退回',
      orderId: order._id
    });
    await user.save();

    // 恢复商品库存
    await Promise.all(order.items.map(async (item) => {
      const product = await Product.findById(item.itemId);
      product.stock += item.quantity;
      await product.save();
    }));

    res.json({ success: true, message: '订单取消成功，积分已退回' });
  } catch (err) {
    res.status(500).json({ success: false, message: '服务器错误', error: err.message });
  }
});

module.exports = router;
// 新增：引入 mongoose 模块（在文件顶部）
const mongoose = require('mongoose');